<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\WechatAutoreply;
use app\common\model\WechatResponse;
use EasyWeChat\Factory;
use app\admin\model\wechat\Config;


/**
 * 首页接口
 */
class Wechat extends Api
{

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    public $subscribe;

    /**
     * 首页
     */
    public function index($id)
    {
        $config = Config::WechatConfig($id);
        $this->subscribe = $config['subscribe'];
        unset($config['subscribe']);
        $app = Factory::officialAccount($config);
        $app->server->push(function($message){
            $event = isset($message['Event']) ? $message['Event'] :'';
            $eventkey = isset($message['EventKey']) ? $message['EventKey'] :'';
            switch ($message['MsgType']) {
                case 'event':
                    return $this->Event($event,$eventkey);
                    break;
                default:
                //自动回复处理
                if ($message['MsgType'] == 'text')
                {
                    return $this->autoreply($message['Content']);
                }
            }
        });
        $app->server->serve()->send();
    }

    /**
     * 事件
     * @param $event
     * @param $eventkey
     * @return mixed|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    protected function Event($event,$eventkey)
    {
        $WechatResponse = new WechatResponse();
        switch ($event) {
            case 'subscribe'://添加关注
                return $this->subscribe ? $this->subscribe :'欢迎关注我们！';
            case 'unsubscribe'://取消关注  业务逻辑
                return '';
            default:
                break;
        }
        //$key[0] 是前缀   $key[1] 二维码的参数
        //比如：qrscene_123123，qrscene_为前缀，后面为二维码的参数值
        $key = explode('_', $eventkey) ;
        if($key[1]!=null){
            return $key[1].'带参数二维码';
        }
        //点击事件 回复文本
        $response = $WechatResponse->where(["eventkey" => $eventkey, 'status' => 'normal'])->find();
        if ($response) {
            $content = (array)json_decode($response['content'], TRUE);
            return $content['content'];
        }
    }

    //自动回复
    protected function autoreply($text)
    {
        $wechat_autoreply = new WechatAutoreply();
        $WechatResponse = new WechatResponse();
        $autoreply = $wechat_autoreply->where(['text' => $text, 'status' => 'normal'])->find();
        if ($autoreply) {
            $response = $WechatResponse->where(["eventkey" => $autoreply['eventkey'], 'status' => 'normal'])->find();
            if ($response) {
                $content = (array)json_decode($response['content'], TRUE);
                return $content['content'];
            }
        }
    }

}
